// pages/login/login.js
import API from '../../api/API.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    phone: '',
    code: '',
    codeStr: '获取验证码',
    disabled: false
  },

  inputPhone: function (e) {
    this.setData({ phone: e.detail.value })
  },

  inputCode: function (e) {
    this.setData({ code: e.detail.value })
  },

  inputName: function (e) {
    this.setData({ name: e.detail.value })
  },

  getCodeNum: function (e) {
    if (!this.data.phone) {
      wx.showToast({
        title: '手机号不能为空',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    const that = this
    const phone = this.data.phone
    const params = {
      mobile: that.data.phone
    }
    API.sendSmsCode(params, function (data) {
      console.log(data)
    }, function (data) {
      
    })
    let num = 60
    console.info(phone)
    let timer = setInterval(function () {
      num--;
      if (num) {
        that.setData({
          codeStr: num + ' s',
          disabled: true
        })
      } else {
        clearInterval(timer)
        that.setData({
          codeStr: '获取验证码',
          disabled: false
        })
      }
    }, 1000)
  },

  login: function () {
    console.log('login')
    if (!this.data.phone) {
      wx.showToast({
        title: '手机号不能为空',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    if (!this.data.code) {
      wx.showToast({
        title: '验证码不能为空',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    const userData = wx.getStorageSync('userData');
    var params = {
      mobile: this.data.phone,
      name: userData.nickName,
      smsCode: this.data.code,
      openId: userData.openId,
      avatar: userData.avatar
    }
    API.login(params, function (data) {
      console.log('登陆成功')
      wx.setStorageSync('token', data);
      wx.navigateBack()
    }, function (result) {
      wx.showToast({
        title: result.message,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})